﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RAP.Framework.Libary.Utils.Grouped
{
  public static class Extensions
  {
    /// <summary>
    /// 将指定集合按指定属性的值转换成分组集合
    /// </summary>
    /// <param name="arr"></param>
    /// <param name="fieldName"></param>
    /// <returns></returns>
    public static IGroupedDictionary ToGroupedDictionary(this IList arr, string fieldName)
    {
      var result = new GroupedDictionary() { GroupField = fieldName };
      var listType = arr.GetType();
      foreach (var item in arr)
      {
        var key = item.GetValue(fieldName);
        var list = result.ToListValue(key, () => listType.CreateInstance<IList>());
        list.Add(item);
      }
      return result;
    }
  }
}
